package edu.nuc.rubikstopwatch;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.SystemClock;
import android.os.Vibrator;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.GestureDetector;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.WindowManager;
import android.widget.TextView;
import edu.nuc.SQLoperation.SQLConstant;
import edu.nuc.SQLoperation.SQLiteHelper;
import edu.nuc.rubikrecord.RubikRecord;
import edu.nuc.rubikrecord.StatsRecord;

public class RubikStopwatchActivity extends Activity {
	final static private boolean DEBUG = true;
	final static private String TAG = "Yans-DEBUG";

	private SQLiteHelper DBHelper = null;
	private TextView timeView = null;
	private TextView upsetFormulaView = null;
	private TextView recentFastView = null;
	private TextView recentAverageView = null;
	private Handler handler = new Handler();
	private long startTime = 0L;
	private long millistime = 0L;
	private static long time = 0L;
	private GestureDetector gestureDetector;
	private int flag = 0;
	private Rubik rubik = new Rubik();

	private Vibrator vibrator;

	private Preferences pref = null;

///=====================>Opreation Tips
	@Override
	protected Dialog onCreateDialog(int id, Bundle args) {
		// TODO Auto-generated method stub
		switch (id) {
		case 0: {
			if (DEBUG) {
				Log.d(TAG, "deal No display dialog on next open");
			}
			return new AlertDialog.Builder(this)
					.setOnKeyListener(new DialogInterface.OnKeyListener() {
						public boolean onKey(DialogInterface dialog,
								int keyCode, KeyEvent event) {
							if (event.getKeyCode() == KeyEvent.KEYCODE_SEARCH) {
								return true;
							}
							return false;
						}
					})
					.setTitle(R.string.dialog_Title)
					.setMessage(R.string.dialog_Message)
					.setPositiveButton(R.string.dialog_Positive,
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int which) {
									removeDialog(0);
								}
							})
					.setNegativeButton(R.string.dialog_Negative,
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int which) {
									removeDialog(0);
									// 记录状态
									pref.closeShowPwdTip();
								}
							})
					.create();
		}
		default:
			break;
		}
		return super.onCreateDialog(id, args);
	}
///=====================>Opreation Tips END	

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		if (DBHelper != null) {
			DBHelper.close();
		}
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.main);
		getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
		time = System.currentTimeMillis();
		DBHelper = new SQLiteHelper(RubikStopwatchActivity.this,
				SQLConstant.DB_NAME, null, 1);

		vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
		timeView = (TextView) findViewById(R.id.timeTextView);
		recentFastView = (TextView) findViewById(R.id.recentFastestTextView);
		recentAverageView = (TextView) findViewById(R.id.recentAverageTextView);

		// 显示打乱公式
		upsetFormulaView = (TextView) findViewById(R.id.upsetFormulaTextView);
		upsetFormulaView.setText(rubik.getUPsetFormula());

		pref = Preferences.getInstance(this);
		// pref.openShowPwdTip();
		if (pref.isShowPwdTip()) {
			if (DEBUG) {
				Log.d(TAG, "startdialg");
			}
			showDialog(0);
		}

		gestureDetector = new GestureDetector(this,
				new SimpleOnGestureListener() {

					// 停止：按下时立刻触发，计时结束
					@Override
					public boolean onDown(MotionEvent e) {
						// TODO Auto-generated method stub
						if (flag == 1) {
							vibrator.vibrate(100);
							handler.removeCallbacks(updateTime);
							flag = 2;
							return true;
						}
						return false;
					}

					// 复位同时记录成绩：长按时触发，记录成绩到数据库，并将时间复位为0，产生新的打乱公式
					@Override
					public void onLongPress(MotionEvent e) {
						super.onLongPress(e);
						// TODO Auto-generated method stub
						if (flag == 2) {
							long[] pattern = { 100, 80, 80, 50 };
							vibrator.vibrate(pattern, -1);

							// System.out.println(millistime);

							ContentValues values = new ContentValues();
							rubik.millisData = System.currentTimeMillis();
							rubik.record = timeView.getText().toString();
							rubik.data = DateFormat.format("yyyy-MM-dd kk:mm",
									rubik.millisData).toString();
							values.put("_score", rubik.record);
							values.put("_millisScore", millistime);
							values.put("_data", rubik.data);
							values.put("_millisData", rubik.millisData);
							values.put("_upsetFormula", rubik.upsetFormula);

							if (DBHelper.insert(values)) {
								timeView.setText(R.string.time);
								upsetFormulaView.setText(rubik.getUPsetFormula());
								StatsRecord stats = new StatsRecord();
								stats.fetchRubik(getApplicationContext(), time);
								recentFastView.setText(getString(R.string.fastest_this_times) + stats.getFastest());
								recentAverageView.setText(getString(R.string.average_this_times) + stats.getAverage());
								startTime = 0L;
								millistime = 0L;
								flag = 0;
							}
						}
					}

					// 开始：按下之后放开时触发，开始计时
					@Override
					public boolean onSingleTapUp(MotionEvent e) {
						// TODO Auto-generated method stub
						if (flag == 0 && startTime == 0L) {
							vibrator.vibrate(200);
							startTime = SystemClock.uptimeMillis();
							handler.postDelayed(updateTime, 100);
							flag = 1;
							return true;
						}
						return false;
					}

				});

	}

	private Runnable updateTime = new Runnable() {

		public void run() {
			// TODO Auto-generated method stub
			millistime = SystemClock.uptimeMillis() - startTime;
			timeView.setText(rubik.parseMillistime(millistime));
			handler.postDelayed(this, 100);
		}
	};

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		// TODO Auto-generated method stub
		return gestureDetector.onTouchEvent(event);
	}

	
//=====================>Menu botton
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// TODO Auto-generated method stub
		menu.add(Menu.NONE, 0, 0, R.string.main_menu_notrecord);
		menu.add(Menu.NONE, 1, 0, R.string.main_menu_record);
		menu.add(Menu.NONE, 2, 0, R.string.Tips);
		menu.add(Menu.NONE, 3, 0, R.string.main_menu_exit);
		return true;
	}

	@Override
	public boolean onMenuItemSelected(int featureId, MenuItem item) {
		// TODO Auto-generated method stub
		switch (item.getItemId()) {
		case 0:
			handler.removeCallbacks(updateTime);
			timeView.setText(R.string.time);
			upsetFormulaView.setText(rubik.getUPsetFormula());
			startTime = 0L;
			flag = 0;
			break;
		case 1:
			Intent recordIntent = new Intent(RubikStopwatchActivity.this,
					RubikRecord.class);
			startActivity(recordIntent);
			break;
		case 2:
			pref.openShowPwdTip();
			showDialog(0);
			break;
		case 3:
			finish();
			break;
		}
		return super.onMenuItemSelected(featureId, item);
	}
//=====================>菜单相关END
	
	
}
